import Token from './token.js'
import router from '../router'
import sys from './config.js'
import { Message } from 'view-ui-plus';

sys.haredot.interceptors.request.use(async function (config) {
    if (config.url !== "/api/token") {
        // 从 Cookie 获取 访问令牌
        try{
            let accessToken = await Token.getAccessToken() ;
            // 请求上必须添加 认证令牌
            config.headers["Authorization"] = "Bearer " + accessToken ;
        } catch (e) {
            router.push({name: "login"});
            throw e;
        }
    }
    return config;
});

sys.haredot.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    if (error.response.status === 403)
        Message.error({background: true, content: "接口权限不足"});
    throw '' ;
});

// 管理所有的接口
const API = {
    // 添加菜单
    addMenu({ name, icon, sorted, description, status }) {
        return sys.haredot.post('/menu/add', { name, icon, sorted, description, status });
    },

    // 查询菜单列表接口
    queryMenuList() {
        return sys.haredot.get("/menu/list") ;
    },
    // 删除菜单状态
    removeMenu(menuId) {
        return sys.haredot.delete("/menu/del" + menuId);
    },

    modifyMenu({id, name, icon, sorted, status, description}) {

        return sys.haredot.put("/menu/" + id, {
            name, icon, sorted, status, description
        });
    },
    addFunc({name, linkUrl, sorted, remark, menuId, status}) {
        // 组装参数格式
        let param = {
            name, linkUrl, sorted, remark, menu: {id: menuId}, status
        };
        // 调用接口
        return sys.haredot.post("/func/add", param);
    },
    queryFuncList(page, limit, params) {
        return sys.haredot.get("/func/list", {params: {page, limits:limit, ...params}});
    },

    modifyFunc({id, name, linkUrl, sorted, remark, menuId, status}) {
        let param = {
            name, linkUrl, sorted, remark, menu: {id: menuId}, status
        };
        return sys.haredot.put("/func/" + id, param) ;
    },

    removeFunc(funcId) {
        return sys.haredot.delete("/func/del" + funcId);
    },

    saveBtn({name, remark, status, funcId}) {
        return sys.haredot.post("/btn/" + funcId , {name, remark, status}) ;
    },
    queryBtnsByFuncID(page, limits, funcId) {
        return sys.haredot.get("/btn/list" + funcId, {params: {page, limits}});
    },

    addDepart({parentId, name, code ,status}) {
        return sys.haredot.post('/depart/add', {parentId, name, code ,status});
    },
    queryDeparts(page, limit) {
        return sys.haredot.get("/depart/list", {params: {page , limit}});
    },
    modifyDepart({id, name, code, status}) {
        return sys.haredot.put("/depart/modify" + id , {name, code, status}) ;
    },

    removeDepart(departId) {
        return sys.haredot.delete('/depart/remove/' + departId) ;
    },

    updateBtnStatus(id, status) {
        return sys.haredot.put("/btn/modify/" + id , {status}, {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        });
    },
    removeBtn(id) {
        return sys.haredot.delete("/btn/remove/" + id);
    },
    queryPositionList() {
        return sys.haredot.get("/position/list");
    },
    addPosition({name, description, status}) {
        return sys.haredot.post("/position/add", {name, description, status});
    },
    modifyPosition({id, name, description, status}) {
        return sys.haredot.put("/position/modify" + id, {name, description, status});
    },
    removePosition(id) {
        return sys.haredot.delete("/position/remove/" + id);
    },
    addRole({name, remark, description, status, defaultRole}) {
        return sys.haredot.post("/role/add" , {name, remark, description, status, defaultRole});
    },
    modifyRole({id, name, remark, description, status, defaultRole}) {
        return sys.haredot.put("/role/modify" + id, {name, remark, description, status, defaultRole});
    },
    queryRoles(){
        return sys.haredot.get("/role/list");
    },
    removeRole(id) {
        return sys.haredot.delete("/role/remove/" + id);
    },
    queryTreeNodes(roleId) {
        return sys.haredot.get("/role/tree/" + roleId);
    },

    bindRolePermission(roleId, treeIds) {
        return sys.haredot.post('/role/bindPermission/' + roleId, treeIds) ;
    },
    queryUsers(page, limits, params) {
        return sys.haredot.get("/user/list", {
            params: {
                page:page, limits,
                ...params
            }
        });
    },
    queryAllDepartsByUserId(userId) {
        let params = userId !=null ? "?uid=" + userId : "" ;
        return sys.haredot.get("/user/departs" + params) ;
    },
    queryAllPositionsByUserId(userId) {
        let params = userId !=null ? "?uid=" + userId : "" ;
        return sys.haredot.get("/user/positions" + params) ;
    },
    bindRoles(userId, roles) {
        return sys.haredot.post("/user/"+ userId +"/roles", [...roles]);
    },
    queryRolesByUserId(userId) {
         // 该用户 ID 可能为 null
        return sys.haredot.get("/user/roles", {params: {uid: userId}}) ;
    },
    saveUser({username, password, realName, tel, birth, email, locked, positions, departs}) {
        return sys.haredot.post("/user/add", {username, password, realName, tel, birth, email, locked, positions, departs}) ;
    },
    modifyUser(id, {password, realName, tel, birth, email, locked, positions, departs}) {
        return sys.haredot.put("/user/modify" + id, {password, realName, tel, birth, email, locked, positions, departs}) ;
    },
    queryServiceLogs(page, limits, params) {
        return sys.haredot.get("/log/service/list", {
            params: {
                page, limits, ...params
            }
        });
    },
    login(username, password) {
        return sys.haredot.post("/api/token", {username, password},{
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        })
    },
    getAccessToken(refreshToken) {
        return sys.haredot.post("/api/token", {refresh: refreshToken},{
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        })
    },
    removeUser(userId) {
        return sys.haredot.delete("/user/remove/" + userId) ;
    },
    queryUsersByDepartId(page, pageSize, departId) {
        return sys.haredot.get("/depart/users/" + departId, {params: {page, limits: pageSize}}) ;
    },
    queryLogs(page, pageSize, params) {
        return sys.haredot.get("/log/log/list", {params: {page, limits: pageSize, ...params}})
    },
    queryLeftMenus() {
        return sys.haredot.get("/menu/leftMenus");
    }
}

// 将接口 API 导出
export default API ;

